import React, {Component} from 'react';
import {Button, Form, Input, Row, Col, Table, Modal, Pagination, DatePicker, Select} from 'antd';
import moment from 'moment';
import {abnormal, excel} from "../value";
import app from '../AppMethod';
import {config} from "../config";
import {Consumer} from "../store";

const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;

class abnormalList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            pagination: {
                current: 0,
                total: 0,
                pagination: 0
            },
            allPage: 0,
            data: [],
            searchData: {}
        }
    };

    columns = [
        {
            title: '订单号',
            dataIndex: 'output_num'
        },
        {
            title: '负责人',
            dataIndex: 'output_follow_name'
        },
        {
            title: '客户名',
            width: '200px',
            dataIndex: 'customer_name'
        },
        {
            title: '类型',
            dataIndex: 'output_type'
        },
        {
            title: '物流类型',
            dataIndex: 'output_logistics'
        },
        {
            title: '下单日期',
            dataIndex: 'output_createtime'
        },
        {
            title: '交货期限',
            dataIndex: 'output_delivery_time'
        },
        {
            title: '异常时间',
            dataIndex: 'abnormal_createtime'
        },
        {
            title: '异常原因',
            dataIndex: 'abnormal_resion'
        },
        {
            title: '异常状态',
            dataIndex: 'abnormal_status',
            render: abnormal_status => {
                return (
                    <span>
                        {
                            abnormal_status == 0 ? <span><span className="c_red"></span>{'未处理'}</span> : ''
                        }
                        {
                            abnormal_status == 1 ? <span><span className="c_green"></span>{'已处理'}</span> : ''
                        }
                    </span>
                )
            }
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                let state = data.abnormal_status;
                let type = data.abnormal_type;
                return (
                    <span>
                        {state == 0 ? <span style={{color: '#1890ff', cursor: 'pointer'}}
                                            onClick={() => this.handleDealOrder(data.abnormal_id)}>{'确认处理'}</span> : ''}
                        {type == 0 ? <span style={{color: '#1890ff', cursor: 'pointer', marginLeft: '10px'}}
                                           onClick={() => this.abnormalDetails(data.abnormal_id)}>{"缺货详情"}</span> : ''}
                        <span style={{color: '#1890ff', cursor: 'pointer', marginLeft: '10px'}}
                              onClick={() => this.handleOrderDetail(data.output_id)}>订单详情</span>
                    </span>
                )
            }
        }
    ];

    render() {
        return (
            <div>
                <Row>
                    <SearchLists
                        clickSearch={(value) => {
                            this.handleGetSearch(value)
                        }}
                        handleReset={() => this.handleReset()}
                        handleLackDetails={() => this.handleLackDetails()}
                        handleExport={(values) => this.handleExport(values)}
                    >
                    </SearchLists>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Table
                        columns={this.columns}
                        rowKey={record => record.abnormal_id}
                        loading={this.state.loading}
                        dataSource={this.state.data}
                        pagination={false}
                    >
                    </Table>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Col span={12} style={{fontSize: '15px'}}>
                        共 {this.state.pagination.total} 条记录 第 {this.state.pagination.current} / {this.state.allPage}
                        页
                    </Col>
                    <Col span={12} style={{textAlign: 'right'}}>
                        <Pagination {...this.state.pagination} showSizeChanger={true} showQuickJumper={true}
                                    hideOnSinglePage={false}
                                    onChange={(page, pageSize) => this.handlePageChange(page, pageSize)}
                                    onShowSizeChange={(current, size) => this.handleSizeChange(current, size)}/>
                    </Col>
                </Row>
            </div>
        )
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({menuType: "异常单列表"});
        this.handleSearchOrderList();
    };

    componentWillUnmount() {
        this.setState = (count, callback) => {
            return;
        };
    };

    /**
     * 跳转到异常详情页面
     * @param id
     */
    abnormalDetails(id) {
        app.setData("abnormalData", JSON.stringify({abnormal_id: id}));
        this.props.history.push(`/index/lackDetails`);
    };

    /**
     * 处理缺货汇总按钮事件
     */
    handleLackDetails() {
        this.props.history.push(`/index/lackDetails`);
    }

    /**
     * 处理订单详情按钮事件
     * @param id
     */
    handleOrderDetail(id) {
        this.props.history.push(`/index/orderDetails/${id}`);
    };

    /**
     * 确认处理按钮事件
     * @param id
     */
    handleDealOrder(id) {
        const _this = this;
        app.post(abnormal.DEAL_WITHABNORMAL, {abnormal_id: id}).then((result) => {
            if (result.code === 1) {
                app.alert(result.msg, 'success', 3);
                _this.handleAfterDeal();
            } else {
                app.alert(result.msg, 'error', 3);
            }
        })
    }

    /**
     * 确认处理后查询订单列表
     */
    handleAfterDeal() {
        let data = this.state.searchData;
        data.page = this.state.pagination.current ? this.state.pagination.current : 1;
        data.size = this.state.pagination.pageSize ? this.state.pagination.pageSize : 10;
        this.handleSearchOrderList(data);
    }

    /**
     * 获取异常单列表
     * @param data
     */
    handleSearchOrderList(data = {page: 1, size: 10}) {
        this.setState({loading: true});
        app.post(abnormal.SEARCH_ABNORMALLIST, data).then((result) => {
            if (result.code === 1) {
                let count = result.data.count;
                let pagination = {
                    current: data.page,
                    pageSize: data.size,
                    total: count
                };
                let allPage;
                if (count % data.size > 0) {
                    allPage = parseInt(count / data.size) + 1;
                } else {
                    allPage = count / data.size;
                }
                let orderData = result.data.dataSet;
                for (let i = 0; i < orderData.length; i++) {
                    orderData[i].output_createtime = orderData[i].output_createtime === null ? '' : moment(orderData[i].output_createtime).format('YYYY-MM-DD');
                    orderData[i].output_delivery_time = orderData[i].output_delivery_time === null ? '' : moment(orderData[i].output_delivery_time).format('YYYY-MM-DD');
                    orderData[i].abnormal_createtime = orderData[i].abnormal_createtime === null ? '' : moment(orderData[i].abnormal_createtime).format('YYYY-MM-DD HH:mm:ss');
                }
                console.log(orderData);
                this.setState({allPage, pagination, data: orderData, loading: false});
            } else {
                let pagination = {
                    current: 0,
                    pageSize: 0,
                    total: 0
                };
                let allPage = 0;
                this.setState({allPage, pagination, data: [], loading: false});
            }
        })
    };

    /**
     * 处理搜索事件
     * @param value
     */
    handleGetSearch(value) {
        let times = value.abnormal_createtime;
        let abnormal_createtime_start = undefined;
        let abnormal_createtime_end = undefined;
        console.log(times);
        if (times != undefined && times.length > 0) {
            abnormal_createtime_start = moment(times[0]._d).format('YYYY-MM-DD');
            abnormal_createtime_end = moment(times[1]._d).format('YYYY-MM-DD');
        }
        let searchData = {
            output_num: value.output_num,
            customer_name: value.customer_name,
            abnormal_status: value.abnormal_status,
            abnormal_type: value.abnormal_type,
            abnormal_createtime_start: abnormal_createtime_start,
            abnormal_createtime_end: abnormal_createtime_end,
        };
        this.setState({searchData});
        searchData.page = 1;
        searchData.size = this.state.pagination.pageSize || 10;
        this.handleSearchOrderList(searchData);
    };

    /**
     * 处理分页跳转事件
     * @param page
     * @param size
     */
    handlePageChange(page, size) {
        let data = this.state.searchData;
        data.page = page;
        data.size = size;
        this.handleSearchOrderList(data);
    };

    /**
     * 处理页数变化事件
     * @param current
     * @param size
     */
    handleSizeChange(current, size) {
        let data = this.state.searchData;
        data.page = current;
        data.size = size;
        this.handleSearchOrderList(data);
    };

    /**
     * 处理重置按钮事件
     */
    handleReset() {
        this.setState({searchData: {}});
        let data = {
            page: 1,
            size: 10,
        };
        this.handleSearchOrderList(data);
    };


    /**
     * 处理导出Excel事件
     * @param value
     */
    handleExport(value) {
        let times = value.abnormal_createtime;
        let abnormal_createtime_start = undefined;
        let abnormal_createtime_end = undefined;
        console.log(times);
        if (times != undefined && times.length > 0) {
            abnormal_createtime_start = moment(times[0]._d).format('YYYY-MM-DD');
            abnormal_createtime_end = moment(times[1]._d).format('YYYY-MM-DD');
        }
        let searchData = {
            output_num: value.output_num,
            customer_name: value.customer_name,
            abnormal_status: value.abnormal_status,
            abnormal_type: value.abnormal_type,
            abnormal_createtime_start: abnormal_createtime_start,
            abnormal_createtime_end: abnormal_createtime_end,
        };
        let params = app.getParams(searchData);
        if (params.length > 0) {
            window.location.href = config.serverUrl + excel.EXPORT_ABNORMALLIST + '?' + params;
        } else {
            window.location.href = config.serverUrl + excel.EXPORT_ABNORMALLIST;
        }
    }
};

/**
 * 搜索组件
 */
class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    };

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <Row>
                    <Form className="login-form">
                        <Row>
                            <Col span={6}>
                                <FormItem label="订单号" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('output_num')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={7}>
                                <FormItem label="客户名" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('customer_name')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={6}>
                                <FormItem label="异常状态" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('abnormal_status')(
                                            <Select placeholder="请选择"
                                                    onChange={(value) => this.handleStatusOnChange(value)}>
                                                <Option value={'0'}>未处理</Option>
                                                <Option value={'1'}>已处理</Option>
                                            </Select>
                                        )
                                    }
                                </FormItem>
                            </Col>

                            <Col span={4} style={{float: 'right'}}>
                                <Button type="primary"
                                        onClick={() => this.handleSearchComplain()}
                                >
                                    查询
                                </Button>
                                <Button type="default"
                                        onClick={() => this.handleReset()}
                                        style={{marginLeft: '10px'}}
                                >
                                    重置
                                </Button>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={6}>
                                <FormItem label="异常原因类型" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('abnormal_type')(
                                            <Select placeholder="请选择"
                                                    onChange={(value) => this.handleTypeOnChange(value)}>
                                                <Option value={'0'}>缺货</Option>
                                                <Option value={'1'}>超时</Option>
                                            </Select>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={7}>
                                <FormItem label="异常时间" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('abnormal_createtime')(
                                            <RangePicker
                                                ranges={{
                                                    Today: [moment(), moment()],
                                                    'This Month': [moment(), moment().endOf('month')]
                                                }}
                                                format="YYYY/MM/DD"
                                                onChange={(dates, dateStrings) => this.handleTimeOnChange(dates, dateStrings)}
                                            />
                                        )
                                    }
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Row>
                <Row>
                    <Button type='primary' onClick={() => this.handleExport()}>导出Excel</Button>
                    <Button type='primary' style={{marginLeft: '10px'}}
                            onClick={() => this.handleCollect()}>缺货汇总</Button>
                </Row>
            </div>
        )
    };

    componentDidMount() {

    };

    /**
     * 获取搜索条件事件
     */
    handleSearchComplain() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 重置按钮事件
     */
    handleReset() {
        this.props.form.resetFields();
        this.props.handleReset();
    };

    /**
     * 获取汇总事件的条件
     */
    handleCollect() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                app.setData("abnormalData", JSON.stringify(values));
                this.props.handleLackDetails();
            }
        })
    };

    /**
     * 获取导出Excel事件的条件
     */
    handleExport() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.handleExport(values);
            }
        })
    };

    /**
     * 处理输入框按下回车键的事件
     */
    handleOnPressEnter() {
        //调用获取搜索条件的函数
        this.handleSearchComplain();
    };

    /**
     * 处理异常状态下拉框选择变化事件
     * @param value
     */
    handleStatusOnChange(value) {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.abnormal_status = value;
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 处理异常原因类型下拉框选择变化事件
     * @param value
     */
    handleTypeOnChange(value) {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.abnormal_type = value;
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 处理日期选择框变化事件
     */
    handleTimeOnChange(dates, dateStrings) {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.abnormal_createtime = dates;
                this.props.clickSearch(values);
            }
        })
    };
}

const SearchLists = Form.create()(SearchList);
const AbnormalLists = Form.create()(abnormalList);
export default prop => (
    <Consumer>
        {
            props => (
                <AbnormalLists {...prop} {...props}/>
            )
        }
    </Consumer>
);